<?php

class Usermodel extends Model
{
	var $user_id = "";
	var $full_name = "";
	var $pwd = "";
	var $email = "";
	var $fb_uid = "";

		//Constructor
		function Usermodel()
		{
				parent::Model();

		}

		function newUser($newUserValues)
		{
				if ($this->checkUserExists($newUserValues['email']) == true)
				{
						$userAvatar = null; //base_url() . 'application/images/default_avatar_thumb.jpg';
						$status = 'pending';
						$about = 'สวัสดี ฉันเพิ่งเข้ามาเป็นสมาชิกใหม่ที่นี่ ช่วยแนะนำฉันด้วยนะ :)';
						$newUserSQL = 'INSERT INTO users
							(username, password, email, user_status, about, avatar, registered_date)
							VALUES
							(	' . $this->db->escape($newUserValues['username']) . ',
								' . $this->db->escape(md5($newUserValues['password'])) . ',
								' . $this->db->escape($newUserValues['email']) . ',
								' . $this->db->escape($status) . ',
								' . $this->db->escape($about) . ',
								' . $this->db->escape($userAvatar) . ',
								' . 'NOW()' . '
							)';
						$this->db->query($newUserSQL);

						return true;
				}
				else
				{
						return false;
				}
		}

		function checkUserExists($email)
		{
				$userCheckingQuery = $this->db->query('SELECT * FROM users WHERE email=' . $this->db->escape($email) . ' LIMIT 0,1');
				if ($userCheckingQuery->num_rows() > 0) return false;
				else  return true;
		}

		function setUserActivationKey($email, $activationKey)
		{
				$this->db->where('email', $email);
				$this->db->update('users', array('activation_key' => $activationKey));
		}

		function setUserActive($activationKey)
		{
				$this->db->where('activation_key', $activationKey);
				$this->db->update('users', array('user_status' => 'active'));
		}
		
		function checkActivationKey($key, $email)
		{
			$this->db->select('activation_key');
			$this->db->where('activation_key', $key);
			$this->db->where('email', $email);
			$query = $this->db->get('users');
			if($query->num_rows() > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		function login($email, $password)
		{
				$loginUserQuery = $this->db->query('SELECT * FROM users WHERE email=' . $this->db->escape($email) . ' LIMIT 0,1');
				if ($loginUserQuery->num_rows() > 0)
				{
						$loginUserRow = $loginUserQuery->result_array();
						if ($loginUserRow[0]['password'] == md5($password))
						{
								if ($loginUserRow[0]['user_status'] == 'active')
								{
										$this->db->query('UPDATE users SET last_login=NOW(), logged_in=1 WHERE user_id=' . $loginUserRow[0]['user_id']);
										$userId = $loginUserRow[0]['user_id'];
										return $userId;
								}
								else  return 'login_error_inactive';
						}
						else  return 'login_error_password';
				}
				else  return 'login_error_email';
		}

		function logout($userId)
		{
				$this->db->where('user_id', $userId);
				$this->db->update('users', array('logged_in' => 0));
		}

	   function validate_user_facebook($uid = 0) {
			//confirm that facebook session data is still valid and matches
			$this->load->library('fb_connect');
			
			//see if the facebook session is valid and the user id in the sesison is equal to the user_id you want to validate
			$session_uid = 'fb:' .  $this->fb_connect->fbSession['uid'];
			if(!$this->fb_connect->fbSession || $session_uid != $uid ) {
				return false;
			}
			
			//Receive Data
			$this->user_id    = $uid;

		  //See if User exists
		  $this->db->where('user_id', $this->user_id);
		  $q = $this->db->get('users');

		  if($q->num_rows == 1) {
			 //yes, a user exists,
			 return true;
		  }

		  //no user exists
		  return false;
	   }

	   function create_user($db_values = '') {
		  $this->user_id       = $db_values["user_id"];
		  $this->full_name  = $db_values["full_name"];
		  $this->pwd           = md5($db_values["pwd"]);
		  $this->email		= $db_values["email"];
		  if(strlen($db_values['fb_uid']) > 0) {
			$this->fb_uid 	   = $db_values['fb_uid'];
		  } else {
			 $this->fb_uid = "";
		  }
		  
		  $new_user_data = array(
			  'user_id'  => $this->user_id,
			  'username'  => $this->full_name,
			  'password'      => $this->pwd,
			  'email'		=> $this->email,
			  'fb_uid' => $this->fb_uid,

		  );
		  
		  $this->db->set('registered_date', 'NOW()', FALSE); // Insert Register timestamp
		  $insert = $this->db->insert('users', $new_user_data);

		  return $insert;
	   }

	   function get_user_by_fb_uid($fb_uid = 0) {
			//returns the facebook user as an array.
			$sql = " SELECT * FROM users WHERE 0 = 0 AND fb_uid = ?";
			$usr_qry = $this->db->query($sql, array('fb:'.$fb_uid));
			
			if($usr_qry->num_rows == 1) {
				//yes, a user exists
				return $usr_qry->result();
			} else {
				// no user exists
				return false;
			}
	   }	


		function getAvatar($userId)
		{
				if ($userId == '') $userId = $this->session->userdata('userId');
				$this->db->select('avatar');
				$this->db->from('users');
				$this->db->where('user_id', $userId);
				$resQuery = $this->db->get();

				if ($resQuery->num_rows() > 0)
				{
						$rowAvatar = $resQuery->result_array();
						$userAvatar = getAvatar($userId, $rowAvatar[0]['avatar']);
						//return $userAvatar;
				}
				else
				{
						$userAvatar = base_url() . 'application/images/default_avatar_thumb.png';
				}
				return $userAvatar;
		}

		function getName($userId)
		{
				if($userId == null){ 
					$this->session->set_flashdata('error',  'ขอโทษด้วย! ระบบไม่สามารถทำตามที่คุณขอได้ ซึ่งปัญหาที่เกิดอาจมีหลายสาเหตุดังนี้ <br />1.คุณกำลังกรอก URL เข้ามาโดยตรงซึ่งเราไม่พบไอดีที่คุณต้องการ <br />2.คุณยังไม่ได้ล๊อกอินเข้าสู่ระบบ.');
					redirect('user/error');
				}
				$nameSql = 'SELECT username FROM users WHERE user_id=' . $userId;
				$nameQuery = $this->db->query($nameSql);
				if ($nameQuery->num_rows() > 0)
				{
						$nameRow = $nameQuery->result_array();
						return $nameRow[0]['username'];
				}
				else  return false;
		}

		function getEmail($userId)
		{
			$sql = 'SELECT email FROM users WHERE user_id=' . $userId;
			$query = $this->db->query($sql);
			if($query->num_rows() > 0)
			{
				$emailRow = $query->result_array();
				return $emailRow[0]['email'];
			}
			else return false;
		}
		
		function getLastlogin($userId)
		{
			$query = $this->db->query('SELECT last_login FROM users WHERE user_id=' . $userId);
			if($query->num_rows() > 0)
			{
				$lastloginRow = $query->row_array();
				return $lastloginRow['last_login'];
			}
			else return false;
		}
		
		function getAbout($userId)
		{
			$query = $this->db->query('SELECT about FROM users WHERE user_id=' . $userId);
			if($query->num_rows() > 0)
			{
				$aboutRow = $query->row_array();
				return $aboutRow['about'];
			}
			else return false;
		}

		function getLat($userId)
		{
			$query = $this->db->query('SELECT latitude FROM users WHERE user_id=' . $userId);
			if($query->num_rows() > 0)
			{
				$latRow = $query->row_array();
				return $latRow['latitude'];
			}
			else return false;
		}

		function getLng($userId)
		{
			$query = $this->db->query('SELECT longitude FROM users WHERE user_id=' . $userId);
			if($query->num_rows() > 0)
			{
				$lngRow = $query->row_array();
				return $lngRow['longitude'];
			}
			else return false;
		}
		
		function getLastUser()
		{
			$orderBy ='registered_date DESC';
			$this->db->select('user_id');
			$this->db->where('user_status', 'active');
			$this->db->order_by($orderBy);
			$this->db->limit(12);
			$query = $this->db->get('users');
			if($query->num_rows() > 0)
			{
				foreach($query->result_array() as $row)
				{
					$user[] = $row;
				}
				return $user;
			}
			else{
				echo "Not members";
			}
		}

		function getFriends($userId, $orderBy = 'datestamp desc', $start = '', $limit = '')
		{
				$friendsArray = array();
				$orderByQuery = '';
				if (trim($orderBy) != '') $orderByQuery = ' ORDER BY ' . $orderBy;
				$query = "SELECT friend_id AS FriendId FROM `friends_list` WHERE user_id='$userId' and approved_status='yes'
					UNION
					SELECT user_id as FriendId FROM `friends_list` WHERE friend_id='$userId' and approved_status='yes'";
				if (trim($limit) != '' && is_numeric($limit))
				{
						if (trim($start) != '' && is_numeric($start)) $query .= ' LIMIT ' . $start . ', ' . $limit;
						else  $query .= ' LIMIT ' . $limit;
				}
				$resFriends = $this->db->query($query);
				if ($resFriends->num_rows() > 0)
				{
						foreach ($resFriends->result_array() as $friendsRow)
						{
								$friendsArray[] = $friendsRow['FriendId'];
						}
				} //end res
				return $friendsArray;
		} //end getFriends()

		function changePwd($userId, $currentPwd, $newPwd)
		{
			$query = $this->db->query('SELECT * FROM users WHERE user_id=' . $userId . ' AND password=' . "'$currentPwd'");
			if($query->num_rows() > 0)
			{
				$this->db->where('user_id', $userId);
				$this->db->update('users', array('password' => $newPwd));
				$this->session->set_flashdata('success',  'ระบบทำการเปลี่ยนรหัสผ่านให้เรียบร้อยแล้ว หลังจากนี้คุณสามารถใช้รหัสผ่านที่ตั้งใหม่ในการเข้าสู่ระบบในครั้งต่อไป.');
				redirect('profile/changePassword');
			}
			else
			{
				$this->session->set_flashdata('error',  'ขออภัย! รหัสผ่านปัจจุบันของคุณไม่ถูกต้อง เพื่อความปลอดภัย ระบบจึงไม่สามารถทำการเปลี่ยนแปลงรหัสผ่านได้.');
				redirect('profile/changePassword');
			}
		}
		

		
		function resetPwd($email)
		{
			$this->load->library('email');
			
		    $chars = "abcdefghijkmnpqrstuvwxyz023456789"; 
		    srand((double)microtime()*1000000); 
		    $i = 1; 
		    $pass = '' ; 
		
		    while ($i <= 6) { 
		        $num = rand() % 33; 
		        $tmp = substr($chars, $num, 1); 
		        $pass = $pass . $tmp; 
		        $i++; 
		    } 
			
			$genPwd = md5($pass);
	
			$query = $this->db->query('SELECT * FROM users WHERE email=' . "'$email'");
			if($query->num_rows() > 0)
			{
				$this->db->where('email', $email);
				$this->db->update('users', array('password' => $genPwd));
				//Send New pwd to email
				$this->email->from('no-reply@panoramap.in.th', 'Panoramap');
				$this->email->to($email);
				$this->email->subject('Reset your password');
				$this->email->message(nl2br('We have reset the password for you. This is your new password: '.$pass. '       Note: You can apply this password to log in next time.'));
				$this->email->send();
				$this->session->set_flashdata('success',  'รีเซ็ตรหัสผ่านเรียบร้อยแล้ว รหัสผ่านใหม่นั้นจะถูกส่งไปที่อีเมล์ของคุณ ซึ่งมันอาจอยู่ใน Junk mail ของคุณ!');
				redirect('reset');
			}
			else
			{
				$this->session->set_flashdata('error',  'ระบบไม่สามารถรีเซ็ตรหัสผ่านให้คุณได้ กรุณาตรวจสอบความถูกต้องอีกครั้ง');
				redirect('reset');
			}
			
		}

	function relativeTime($dt,$precision=2)
	{
		if(is_string($dt)) $dt=strtotime($dt);

		$times=array(	365*24*60*60	=> "ปี",
						30*24*60*60		=> "เดือน",
						7*24*60*60		=> "อาทิตย์",
						24*60*60		=> "วัน",
						60*60			=> "ชั่วโมง",
						60				=> "นาที",
						1				=> "วินาที");
		
		$passed=time()-$dt;
		
		if($passed<59)
		{
			$output='เมื่อกี้นี้';
		}
		else
		{
			$output=array();
			$exit=0;
			
			foreach($times as $period=>$name)
			{
				if($exit>=$precision || ($exit>0 && $period<60)) break;
				
				$result = floor($passed/$period);
				if($result>0)
				{
					$output[]=$result.' '.$name;
					$passed-=$result*$period;
					$exit++;
				}
				else if($exit>0) $exit++;
			}
					
			$output=implode(' ',$output).'ที่แล้ว';
		}
		
		return $output;
	}

}